<template>
    <div class="rider-platform">
        <!-- 顶部导航 -->
        <el-header class="platform-header">
            <div class="header-content">
                <div class="header-left">
                    <img src="../../assets/logo.png" alt="logo" class="logo">
                    <span class="platform-title">骑手工作台</span>
                </div>
                <div class="header-right">
                    <span class="rider-info">欢迎，{{ riderName }}</span>
                    <el-button @click="logout" type="danger" size="small">退出登录</el-button>
                </div>
            </div>
        </el-header>

        <!-- 主要内容区域 -->
        <el-container class="main-container">
            <!-- 侧边栏 -->
            <el-aside class="sidebar" width="200px">
                <el-menu
                    :default-active="activeMenu"
                    class="el-menu-vertical"
                    @select="handleMenuSelect"
                >
                    <el-menu-item index="available">
                        <i class="el-icon-shopping"></i>
                        <span slot="title">待接订单</span>
                    </el-menu-item>
                    <el-menu-item index="my-orders">
                        <i class="el-icon-truck"></i>
                        <span slot="title">我的订单</span>
                    </el-menu-item>
                </el-menu>
            </el-aside>

            <!-- 内容区域 -->
            <el-main class="content-area">
                <!-- 待接订单页面 -->
                <div v-if="activeMenu === 'available'" class="page-content">
                    <div class="page-header">
                        <h2>待接订单</h2>
                        <el-button @click="refreshAvailableOrders" type="primary" icon="el-icon-refresh">刷新</el-button>
                    </div>
                    
                    <el-table 
                        :data="availableOrders" 
                        style="width: 100%"
                        v-loading="loadingAvailable"
                        empty-text="暂无待接订单"
                    >
                        <el-table-column prop="orderId" label="订单号" width="120"></el-table-column>
                        <el-table-column prop="buyerName" label="买家" width="100"></el-table-column>
                        <el-table-column prop="sellerName" label="卖家" width="100"></el-table-column>
                        <el-table-column prop="productName" label="商品名称" width="200"></el-table-column>
                        <el-table-column prop="totalPrice" label="订单金额" width="100">
                            <template slot-scope="scope">
                                ¥{{ scope.row.totalPrice }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="deliveryAddress" label="收货地址" width="250"></el-table-column>
                        <el-table-column prop="createTime" label="创建时间" width="180">
                            <template slot-scope="scope">
                                {{ formatDateTime(scope.row.createTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120">
                            <template slot-scope="scope">
                                <el-button 
                                    @click="acceptOrder(scope.row.orderId)" 
                                    type="success" 
                                    size="small"
                                >
                                    接单
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 我的订单页面 -->
                <div v-if="activeMenu === 'my-orders'" class="page-content">
                    <div class="page-header">
                        <h2>我的订单</h2>
                        <el-button @click="refreshMyOrders" type="primary" icon="el-icon-refresh">刷新</el-button>
                    </div>
                    
                    <el-table 
                        :data="myOrders" 
                        style="width: 100%"
                        v-loading="loadingMyOrders"
                        empty-text="暂无配送订单"
                    >
                        <el-table-column prop="orderId" label="订单号" width="120"></el-table-column>
                        <el-table-column prop="buyerName" label="买家" width="100"></el-table-column>
                        <el-table-column prop="sellerName" label="卖家" width="100"></el-table-column>
                        <el-table-column prop="productName" label="商品名称" width="200"></el-table-column>
                        <el-table-column prop="totalPrice" label="订单金额" width="100">
                            <template slot-scope="scope">
                                ¥{{ scope.row.totalPrice }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="deliveryAddress" label="收货地址" width="250"></el-table-column>
                        <el-table-column prop="deliveryStatus" label="配送状态" width="120">
                            <template slot-scope="scope">
                                <el-tag :type="getStatusType(scope.row.deliveryStatus)">
                                    {{ getStatusText(scope.row.deliveryStatus) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="pickupTime" label="接单时间" width="180">
                            <template slot-scope="scope">
                                {{ formatDateTime(scope.row.pickupTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120">
                            <template slot-scope="scope">
                                <el-button 
                                    v-if="scope.row.deliveryStatus === 'IN_TRANSIT'"
                                    @click="completeOrder(scope.row.orderId)" 
                                    type="primary" 
                                    size="small"
                                >
                                    完成配送
                                </el-button>
                                <span v-else>已完成</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script>
export default {
    name: "platform-rider",
    data() {
        return {
            activeMenu: 'available',
            riderName: '',
            availableOrders: [],
            myOrders: [],
            loadingAvailable: false,
            loadingMyOrders: false
        };
    },
    created() {
        this.checkAuth();
        this.getRiderInfo();
        this.loadAvailableOrders();
    },
    methods: {
        // 检查认证
        checkAuth() {
            const token = localStorage.getItem('rider_token');
            if (!token) {
                this.$message.error('请先登录');
                this.$router.replace('/login-rider');
                return;
            }
        },

        // 获取骑手信息
        getRiderInfo() {
            this.riderName = this.$sta.riderName || '骑手';
        },

        // 菜单选择
        handleMenuSelect(key) {
            this.activeMenu = key;
            if (key === 'available') {
                this.loadAvailableOrders();
            } else if (key === 'my-orders') {
                this.loadMyOrders();
            }
        },

        // 加载待接订单
        loadAvailableOrders() {
            this.loadingAvailable = true;
            this.$api.getAvailableOrders()
                .then(res => {
                    if (res.code === 200) {
                        this.availableOrders = res.data || [];
                    } else {
                        this.$message.error(res.message || '获取订单失败');
                    }
                })
                .catch(err => {
                    console.error('获取待接订单失败:', err);
                    this.$message.error('获取订单失败');
                })
                .finally(() => {
                    this.loadingAvailable = false;
                });
        },

        // 加载我的订单
        loadMyOrders() {
            this.loadingMyOrders = true;
            this.$api.getRiderMyOrders()
                .then(res => {
                    if (res.code === 200) {
                        this.myOrders = res.data || [];
                    } else {
                        this.$message.error(res.message || '获取订单失败');
                    }
                })
                .catch(err => {
                    console.error('获取我的订单失败:', err);
                    this.$message.error('获取订单失败');
                })
                .finally(() => {
                    this.loadingMyOrders = false;
                });
        },

        // 接单
        acceptOrder(orderId) {
            this.$confirm('确认接收此订单？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.acceptOrder(orderId)
                    .then(res => {
                        if (res.code === 200) {
                            this.$message.success('接单成功');
                            this.loadAvailableOrders(); // 刷新待接订单
                            this.loadMyOrders(); // 刷新我的订单
                        } else {
                            this.$message.error(res.message || '接单失败');
                        }
                    })
                    .catch(err => {
                        console.error('接单失败:', err);
                        this.$message.error('接单失败');
                    });
            });
        },

        // 完成订单
        completeOrder(orderId) {
            this.$confirm('确认完成配送？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.completeOrder(orderId)
                    .then(res => {
                        if (res.code === 200) {
                            this.$message.success('订单完成');
                            this.loadMyOrders(); // 刷新我的订单
                        } else {
                            this.$message.error(res.message || '操作失败');
                        }
                    })
                    .catch(err => {
                        console.error('完成订单失败:', err);
                        this.$message.error('操作失败');
                    });
            });
        },

        // 刷新待接订单
        refreshAvailableOrders() {
            this.loadAvailableOrders();
        },

        // 刷新我的订单
        refreshMyOrders() {
            this.loadMyOrders();
        },

        // 格式化日期时间
        formatDateTime(dateTime) {
            if (!dateTime) return '';
            return new Date(dateTime).toLocaleString('zh-CN');
        },

        // 获取状态类型
        getStatusType(status) {
            const typeMap = {
                'IN_TRANSIT': 'warning',
                'DELIVERED': 'success'
            };
            return typeMap[status] || 'info';
        },

        // 获取状态文本
        getStatusText(status) {
            const textMap = {
                'IN_TRANSIT': '配送中',
                'DELIVERED': '已送达'
            };
            return textMap[status] || status;
        },

        // 退出登录
        logout() {
            this.$confirm('确认退出登录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                localStorage.removeItem('rider_token');
                this.$sta.isLogin = false;
                this.$sta.riderId = '';
                this.$sta.riderName = '';
                this.$router.replace('/login-rider');
                this.$message.success('已退出登录');
            });
        }
    }
};
</script>

<style scoped>
.rider-platform {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.platform-header {
    background-color: #409EFF;
    color: white;
    padding: 0 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100%;
}

.header-left {
    display: flex;
    align-items: center;
}

.logo {
    width: 40px;
    height: 40px;
    margin-right: 10px;
}

.platform-title {
    font-size: 20px;
    font-weight: 600;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 15px;
}

.rider-info {
    font-size: 14px;
}

.main-container {
    flex: 1;
    height: calc(100vh - 60px);
}

.sidebar {
    background-color: #f5f5f5;
    border-right: 1px solid #e6e6e6;
}

.el-menu-vertical {
    height: 100%;
    border-right: none;
}

.content-area {
    padding: 20px;
    background-color: #fafafa;
}

.page-content {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e6e6e6;
}

.page-header h2 {
    margin: 0;
    color: #303133;
}

.el-table {
    margin-top: 10px;
}
</style> 